package com.hky.front_end_monitor.utils;

import java.text.NumberFormat;

/**
 * @auther Gpu is all you need
 * @date 2022/7/29
 */
public class NumberUtils {
    public static Double toDouble(Object object) {
        if (object == null) return -1D;
        if (object instanceof Integer)
            return ((Integer) object).doubleValue();
        if (object instanceof String) {
            String s = (String) object;
            if (object != "" && ableToCaseNumber(s)) {
                return Double.parseDouble((String) object);
            }
            return -1D;
        }
        return (Double) object;
    }

    public static Integer toInteger(Object object) {
        if (object == null) return -1;
        if (object instanceof String) {
            String s = (String) object;
            if (object != "" && ableToCaseNumber(s)) {
                return Integer.parseInt(s);
            }
            return -1;
        }
        if (object instanceof Integer) return (Integer) object;
        return -1;
    }

    public static Long toLong(Object object) {
        if (object == null) return -1L;
        if (object instanceof String) {
            String s = (String) object;
            if (object != "" && ableToCaseNumber(s)) {
                return Long.parseLong(s);
            }
            return -1L;
        }
        if (object instanceof Long) return (Long) object;
        return -1L;
    }

    private static boolean ableToCaseNumber(String s) {
        boolean flag = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= '0' && c <= '9') {
                flag = true;
                break;
            }
        }
        return flag;
    }
}
